package org.goldenport.g3.channels.twitter

import java.io.InputStream
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.{ClientProtocolException, ResponseHandler}
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.{DefaultHttpClient}
import oauth.signpost._
import oauth.signpost.basic._
import org.goldenport.g3._
import org.goldenport.g3.atom._

/**
 * @since   May. 30, 2010
 * @version Sep. 16, 2010
 * @author  ASAMI, Tomoharu
 */
class TwitterAdapter() extends G3Adapter() {
  lazy val auth = context.getAuthentication("http://twitter.com/")

  protected override def do_Action(content: AnyRef, parcel: G3Parcel, ctx: G3AgentContext): AnyRef = {
    val httpclient = new DefaultHttpClient()
    var is: InputStream = null;
    try {
      val httpget = make_httpget
      val response = httpclient.execute(httpget)
      val entity = response.getEntity()
      is = entity.getContent()
      AtomFeed(is)
    } finally {
      if (is != null) {
        is.close()
      }
      httpclient.getConnectionManager().shutdown()
    }
  }

  private def make_httpget = {
    auth match {
      case Some(bauth: BasicAuthentication) => {
        val user = bauth.user
        val password = bauth.password
        val uri = "http://%s:%s@twitter.com/statuses/user_timeline/%s.atom".format(user, password, user)
        new HttpGet(uri)
      }
      case Some(oauth: OAuthAuthentication) => {
        val user = oauth.user
        val consumerkey = oauth.consumerKey
        val consumersecret = oauth.consumerSecret
        val accesstoken = oauth.accessToken.get
        val accesstokensecret = oauth.accessTokenSecret.get
        val consumer = new DefaultOAuthConsumer(consumerkey, consumersecret)
        consumer.setTokenWithSecret(accesstoken, accesstokensecret)
        val httpget = new HttpGet("http://twitter.com/statuses/user_timeline/%s.atom".format(user))
        consumer.sign(httpget)
        httpget
      }
      case None => error(auth.toString)
    }    
  }
}

trait TwitterContext extends G3Module {
  def twitter(atom: Symbol): G3Channel = {
    add_channel_node(atom, context.createChannel(new TwitterAdapter()))
  }
}
